package test3_tx.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import test3_tx.dao.AccountDao;
import test3_tx.service.AccountService;
import test3_tx.service.LogService;


@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private LogService logService;


    public void transfer(String out, String in, Double money) {
            try {
                accountDao.outMoney(out, money);
                accountDao.inMoney(in, money);
            }finally {
                logService.log(out+"向"+in+"转账"+money+"元");
            }
    }

    public void transfer_exc(String out, String in, Double money) {
            accountDao.outMoney(out,money);
            //模拟中途出现错误,此时会出现，out的钱减少了，但是in的钱并没有增加。
            int a=1/0;
            accountDao.inMoney(in,money);
    }


    //使该方法具备事务性
    @Transactional
    public void transfer_tx(String out, String in, Double money) {
        try {
            accountDao.outMoney(out, money);
            //模拟中途出现错误,此时会出现，out的钱减少了，但是in的钱并没有增加。
            int a = 1 / 0;
            accountDao.inMoney(in, money);
        }finally {
            //无论成功与否，记录日志
            //除此之外，还需要在对应方法的注解上配置单独开启事务，否则这个操作会随着当前事务回滚
            logService.log(out+"向"+in+"转账"+money+"元");
        }
    }


}
